//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//********************************************************* 

using System;
using System.Collections;
using System.Runtime.InteropServices;
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Word;

namespace Microsoft.TridentWordAddIn.AddIn
{
    public static class DocumentExtension
    {
        private static string CustomXMLNamespace = "Microsoft.TridentWordAddIn.AddIn";

        /// <summary>
        /// GUIDs from custom XML part.
        /// </summary>
        /// <param name="document">The document.</param>
        /// <param name="createIfMissing">if set to <c>true</c> [create if missing].</param>
        /// <returns></returns>
        public static Guid? GuidFromCustomXmlPart(this _Document document, bool createIfMissing)
        {
            try
            {
                CustomXMLParts namespaceParts = document.CustomXMLParts.SelectByNamespace(CustomXMLNamespace);
                if (createIfMissing && namespaceParts.Count == 0)
                {
                    Guid newKey = Guid.NewGuid();
                    namespaceParts.Add("<documentKey xmlns=\"" + CustomXMLNamespace + "\">" + newKey + "</documentKey>",
                                       Type.Missing);
                    return newKey;
                }

                if (namespaceParts.Count > 0)
                {
                    IEnumerator iter = namespaceParts.GetEnumerator();
                    iter.MoveNext();
                    CustomXMLPart part = (CustomXMLPart)iter.Current;
                    Guid result = new Guid(part.DocumentElement.Text);
                    return result;
                }
             
                return null;
            }
            catch (COMException)
            {
                return null;
            }
        }
    }
}
